// @algorithm @lc id=100347 lang=cpp
// @title er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof

#include "algm/algm.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *ans;
    TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
        dfs(root, p, q);
        return ans;
    }

    bool dfs(TreeNode *root, TreeNode *p, TreeNode *q) {
        if (root == nullptr) {
            return false;
        }
        bool leftSon = dfs(root->left, p, q);
        bool rightSon = dfs(root->right, p, q);
        if ((leftSon && rightSon) || ((root->val == p->val || root->val == q->val) && (leftSon || rightSon))) {
            ans = root;
        }
        return leftSon || rightSon || (root->val == p->val || root->val == q->val);
    }
};